<template>
    <div class="article-editor card">
        <el-form :model="articleForm" ref="formRef" label-width="80px" @submit.prevent="saveArticle">
            <el-form-item label="标题">
                <el-input v-model="articleForm.title" />
            </el-form-item>

            <el-form-item label="分类">
                <el-select v-model="articleForm.categoryId" placeholder="请选择分类">
                    <el-option v-for="category in categories" :key="category.id" :label="category.name"
                        :value="category.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="内容">
                <el-input type="textarea" v-model="articleForm.content" rows="10" />
            </el-form-item>

            <el-form-item label="标签">
                <div class="selected-tags-preview">
                    <span v-for="tag in receivedTags" :key="tag.id" class="tag-preview">
                        {{ tag.name }}
                    </span>
                </div>
            </el-form-item>

            <!-- 按钮组移到右侧 -->
            <el-form-item class="button-group-right">
                <div class="flex justify-end space-x-2">
                    <el-button type="primary" native-type="submit">发布文章</el-button>
                    <el-button @click="cancelEdit">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import http from '@/http'
import router from '@/router'
const route = useRoute()
import { useRouter } from 'vue-router'
let backmy = useRouter()
const receivedTags = ref([])
const categories = ref([])
const articleForm = ref({
    title: '',
    content: '',
    categoryId: null
})
const formRef = ref(null)
const isSubmitting = ref(false) // 添加加载状态

onMounted(() => {
    fetchCategories()
    const tagStr = route.query.tags
    if (tagStr) {
        receivedTags.value = JSON.parse(tagStr)
    }
})

const fetchCategories = async () => {
    try {
        const response = await http.get('cate/')
        categories.value = response.data.data
    } catch (error) {
        console.error('获取分类失败:', error)
        ElMessage.error('加载分类失败，请刷新页面')
    }
}

const saveArticle = async () => {
    if (isSubmitting.value) return // 防止重复提交

    if (
        !articleForm.value.title ||
        !articleForm.value.content ||
        !articleForm.value.categoryId
    ) {
        ElMessage.warning('请填写完整信息（标题、内容、分类）')
        return
    }

    try {
        isSubmitting.value = true

        const articleData = {
            ...articleForm.value,
            tagIds: receivedTags.value.map(tag => tag.id)
        }

        const response = await http.post('article/publish/', articleData)

        if (response.data.code === 200) {
            ElMessage.success('文章发布成功！')
            articleForm.value = {
                title: '',
                content: '',
                categoryId: null
            }
            receivedTags.value = []
            router.push('myself/cate')
        } else if (response.data.code === 400) {
            ElMessage.warning('所选分类不存在，请刷新页面后重试')
        } else if (response.data.code === 500) {
            ElMessage.error('服务器繁忙，请稍后重试')
        } else {

            ElMessage.error(response.data.msg || '发布失败，请重试')
        }
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('网络请求失败，请检查网络连接')
    } finally {
        isSubmitting.value = false
    }
}

const cancelEdit = () => {
    ElMessageBox.confirm('确定要取消编辑吗？未保存的内容将丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        articleForm.value = {
            title: '',
            content: '',
            categoryId: null
        }
        receivedTags.value = []
    }).catch(() => {
    })
}
</script>

<style scoped>
.article-editor {
    padding: 20px;
    background: linear-gradient(to right, #e3f2fd, #fce4ec);
    border-radius: 8px;
}

.selected-tags-preview {
    margin-top: 10px;
    padding: 10px;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 4px;
}

.tag-preview {
    display: inline-block;
    margin-right: 8px;
    padding: 4px 8px;
    background-color: #ffffff;
    color: #333;
    border-radius: 12px;
    font-size: 12px;
}

.button-group-right {
    display: flex;
    justify-content: flex-end;
}
</style>